from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import config

#数据库
db = SQLAlchemy()

#登录模块
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'

def create_app(config_name='default'):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    #将扩展对象绑定到应用上
    db.init_app(app)
    login_manager.init_app(app)

    # 注册授权服务蓝本
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    # 注册REST Web服务蓝本
    from .api import api as api_1_0_blueprint
    app.register_blueprint(api_1_0_blueprint, url_prefix='/api')

    # 注册广告展示蓝本
    from .show import show as show_blueprint
    app.register_blueprint(show_blueprint, url_prefix='/show')

    # 注册admin后台管理蓝本
    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    # 推送app上下文环境
    app.app_context().push()
    db.create_all()

    return app